package gosnoopers.fr;

import java.util.ArrayList;
import java.util.HashMap;

import lazy_listview.JSONfunctions;
import listview.CitiesAdapter;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.CheckBox;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import common.Common;

 
 
public class Cities extends Activity {
	public static String URL = "http://gosnoopers.com/province/getProvinceByCountryId?CountryId=14";
	
	ProgressDialog mProgressDialog;
    ArrayList<HashMap<String, String>> arraylist;
    static String ID = "id";
    static String NAME = "name";
    static String ALIAS = "alias";
    public static JSONObject jsonobject;
    public static JSONArray jsonarray;
    ListView list;
	
	CitiesAdapter adapter;
	public static String strCityId = "";
    public  boolean isNetworkAvailable() {
        ConnectivityManager connectivityManager 
              = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
        return activeNetworkInfo != null && activeNetworkInfo.isConnected();
    }
    /** Called when the activity is first created. */
       
      @Override
      public void onCreate(Bundle savedInstanceState) {
          super.onCreate(savedInstanceState);
          this.requestWindowFeature(Window.FEATURE_NO_TITLE);
          setContentView(R.layout.cities);
          
          LandingActivity.cities = "";
          
          
          Intent iin= getIntent();
          Bundle b = iin.getExtras();
          String country_name  = "";
          String country_id  = "";
          URL = "http://gosnoopers.com/province/getProvinceByCountryId";
          if(b!=null)
          {
        	  country_name =(String) b.get("COUNTRY_NAME");
        	  country_id =(String) b.get("ID_COUNTRY");
        	  URL = "http://gosnoopers.com/province/getProvinceByCountryId?CountryId="+country_id;
              
          }
          String TextHeader = country_name;
          TextView text = (TextView) findViewById(R.id.text_view_landing_page_header);
          text.setText(TextHeader);
          
          if(!isNetworkAvailable()){
	    	  
	    	  Toast toast = Toast.makeText(getApplicationContext(), Common.MSG, Toast.LENGTH_SHORT);
	    	  toast.show();
	      }else{
	    	  new DownloadJSON().execute();
	      }
          
          
          ImageView image_done = (ImageView) findViewById(R.id.image_done);
          image_done.setClickable(true);
          image_done.setOnClickListener(new OnClickListener() {
              @Override
              public void onClick(View v) {
                  	HomePage.page = 1;
					Intent goToNextActivity = new Intent(getApplicationContext(), HomePage.class);
					goToNextActivity.putExtra("provin_id", LandingActivity.cities);
					startActivity(goToNextActivity);
              }
          });
          
      }
   // DownloadJSON AsyncTask
      private class DownloadJSON extends AsyncTask<Void, Void, Void> {
   
          @Override
          protected void onPreExecute() {
              super.onPreExecute();
              ProgressBar mProBarLoading = (ProgressBar)findViewById(R.id.probar_loading);
              mProBarLoading.setVisibility(View.VISIBLE);
          }
   
          @Override
          protected Void doInBackground(Void... params) {
              // Create an array
              arraylist = new ArrayList<HashMap<String, String>>();
              // Retrieve JSON Objects from the given URL address
              
              jsonobject = JSONfunctions.getJSONfromURL(URL);
              
              try {
                  // Locate the array name in JSON
                  jsonarray = jsonobject.getJSONArray("data");
                  boolean strError = jsonobject.getBoolean("error");
                  String message = jsonobject.getString("message");
                  if(!strError){
                  	for (int i = 0; i < jsonarray.length(); i++) {
                          HashMap<String, String> map = new HashMap<String, String>();
                          jsonobject = jsonarray.getJSONObject(i);
                          // Retrive JSON Objects
                          map.put("id", jsonobject.getString("Id"));
                          map.put("name", jsonobject.getString("Name"));
                          map.put("alias", jsonobject.getString("Alias"));
                          
                          // Set the JSON Objects into the array
                          arraylist.add(map);
                      }
                  	
                  }else{
                  	Toast toast = Toast.makeText(getApplicationContext(), message, Toast.LENGTH_SHORT);
        	    	  	toast.show();
                  }
                  
              } catch (JSONException e) {
                  Log.e("Error", e.getMessage());
                  e.printStackTrace();
              }
              return null;
          }
   
          @Override
          protected void onPostExecute(Void args) {
              // Locate the listview in listview_main.xml
        	  ProgressBar mProBarLoading = (ProgressBar)findViewById(R.id.probar_loading);
              mProBarLoading.setVisibility(View.GONE);
          	list = (ListView) findViewById(R.id.list);
              // Pass the results into ListViewAdapter.java
              adapter = new CitiesAdapter(Cities.this, arraylist);
              // Set the adapter to the ListView
              list.setAdapter(adapter);

              list.setOnItemClickListener(new OnItemClickListener() {



  				@Override
  				public void onItemClick(AdapterView<?> arg0, View view,
  						int position, long id) {
  					// TODO Auto-generated method stub
  	                 // ListView Clicked item index
  	                 int itemPosition     = position;
  	                 
  	                  TextView id_city = (TextView) view.findViewById(R.id.id_city);
  	                  TextView name = (TextView) view.findViewById(R.id.name);
  	                  CheckBox checkBox = (CheckBox) view.findViewById(R.id.checkBoxCityName);
  	                  
  	                LandingActivity.cities = id_city+",";

  	               
  				}

              }); 
          }
      }
}